<template>
    <div>
      <div class="project-collapse" v-for="(role, index) in rolesOrder" v-bind:key="index" v-if="roles.includes(role)">
        <el-collapse v-if="tableData[role]">
          <el-collapse-item>
            <template slot="title">
              <div class="collapse-head-slot">
                <div class="collapse-head-title" :class="role.toLowerCase() + '-color'">
                  As the {{ role }}
                  <span style="margin-left: 12px; color: rgb(140 140 140); font-size: 18px;">( Total {{ tableData[role].total }} items )</span>
                  <!-- <i class="collapse-head-icon el-icon-arrow-right"></i> -->
                </div>
              </div>
            </template>
            <div>
              <el-table class="collapse-table-body" row-key="id"
                :data="tableData[role].list"
                v-loading="tableData[role].tableLoading"
                v-if="role === 'SCREENWRITER'"
                @expand-change="scTableExpandChange"
              >
                <el-table-column label="" width="30"></el-table-column>
                <el-table-column type="expand">
                  <template slot-scope="props">
                    <!-- ----------剧本 子表格------------ -->
                    <div class="sc-child-table-div" >
                      <el-table class="child-table-body" border :data="props.row.child.list" v-loading="props.row.child.tableLoading">
                        <el-table-column label="Project Name" min-width="200">
                          <template slot-scope="scope">
                            <span>{{ scope.row.projectResponse.name }}</span>
                          </template>
                        </el-table-column>
                        <el-table-column label="Project Team Member" min-width="300">
                          <template slot-scope="scope" v-if="scope.row.PRODUCER">
                            <div class="p-members-cell">
                              <div class="p-m-item producer">
                                <el-avatar class="member-avatar" :src="userInfoCach[scope.row.PRODUCER.userId].avatarImage" :size="50">{{ scope.row.PRODUCER.userId.slice(0, 1) }}</el-avatar>
                                <div class="p-m-right">
                                  <span class="member-name">{{ scope.row.PRODUCER.userId }}</span>
                                  <span class="member-roles">PRODUCER</span>
                                </div>
                              </div>
                              <el-popover placement="right" trigger="hover" @show="pMembersShow(scope.row)" transition="el-zoom-in-bottom">
                                <div
                                  class="p-member-list"
                                  v-loading="!scope.row.members || scope.row.members.length === 0"
                                  v-infinite-scroll="
                                    () => {
                                      memberLoad(scope.row);
                                    }
                                  "
                                  :infinite-scroll-disabled="infiniteScrollDisabled"
                                  :infinite-scroll-immediate="false"
                                >
                                  <el-row type="flex" style="flex-wrap: wrap; justify-content: flex-start;">
                                    <el-col :span="scope.row.members.length > 5 ? 12 : 24" v-for="(m, ind) in scope.row.members" v-bind:key="ind">
                                      <div class="p-m-item">
                                        <el-avatar class="member-avatar" :src="userInfoCach[m.userId].avatarImage" :size="50">{{ m.userId.slice(0, 1) }}</el-avatar>
                                        <div class="p-m-right">
                                          <span class="member-name">{{ m.userId }}</span>
                                          <span class="member-roles">{{ m.role }}</span>
                                        </div>
                                      </div>
                                    </el-col>
                                  </el-row>
                                </div>
                                <div class="p-m-avatars" slot="reference">
                                  <div class="member-more"></div>
                                  <div class="member-more"></div>
                                  <div class="member-more"></div>
                                </div>
                              </el-popover>
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column label="Project Status" min-width="300">
                          <template slot-scope="scope">
                            <div class="tag-div" :class="formatTagColor(scope.row.projectResponse.status)">
                              {{ scope.row.projectResponse.status }}
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column label="Action" min-width="200">
                          <template slot-scope="scope">
                            <div class="action-btns">
                              <el-tooltip class="item" effect="dark" content="Detail" placement="top" transition="el-zoom-in-bottom">
                                <el-button type="text" :disabled="scope.row.projectResponse.completed"
                                  @click="jumpRolePage(props.row, 'Screenwriter', 'project')"
                                >
                                  <div class="img-btn project-detail"></div>
                                </el-button>
                              </el-tooltip>
                              <el-tooltip class="item" effect="dark" content="Member Setting" placement="top" transition="el-zoom-in-bottom">
                                <el-button type="text"
                                  @click="pageJump('/filmmaking/producer/roleList', scope.row)"
                                >
                                  <div class="img-btn member-set"></div>
                                </el-button>
                              </el-tooltip>
                              <el-dropdown placement="bottom" @command="e => {projectCommand(e, scope.row, 'child')}">
                                <el-button type="text" style="margin-left: 10px;">
                                  <div class="img-btn more"></div>
                                </el-button>
                                <el-dropdown-menu slot="dropdown">
                                  <el-dropdown-item command="feedback" :disabled="!checkActionDisabled('Feedback', scope.row)">
                                    <div class="dropdown-item-div">
                                      <span class="dropdown-item-icon feedback"></span>
                                      <span>Feedback</span>
                                    </div>
                                  </el-dropdown-item>
                                  <el-dropdown-item command="sow" :disabled="!checkActionDisabled('SOW', scope.row)">
                                    <div class="dropdown-item-div" v-if="!scope.row.signedSow">
                                      <span class="dropdown-item-icon"></span>
                                      <span>SOW</span>
                                    </div>
                                    <div class="dropdown-item-div" v-else>
                                      <span class="dropdown-item-icon"></span>
                                      <span>VIEW SOW</span>
                                    </div>
                                  </el-dropdown-item>
                                  <el-dropdown-item command="quit" divided :disabled="!checkActionDisabled('Quit Project', scope.row)">
                                    <div class="dropdown-item-div">
                                      <span class="dropdown-item-icon stop"></span>
                                      <span>Quit Project</span>
                                    </div>
                                  </el-dropdown-item>
                                </el-dropdown-menu>
                              </el-dropdown>
                            </div>
                          </template>
                        </el-table-column>
                      </el-table>
                      <div class="pagination">
                        <el-pagination
                          background
                          layout="prev, pager, next"
                          :hide-on-single-page="true"
                          :page-size="6"
                          :total="props.row.child.total"
                          @current-change="
                            e => {
                              paginationChange(e, 'child', props.row);
                            }
                          "
                        ></el-pagination>
                      </div>
                    </div>
                    <!-- ----------剧本 子表格 end------------ -->
                  </template>
                </el-table-column>
                <el-table-column label="Script Name" min-width="300">
                  <template slot-scope="scope">
                    <span>{{ scope.row.name }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="Writing Status" min-width="300">
                  <template slot-scope="scope">
                    <div class="tag-div" :class="formatTagColor(scope.row.status)">
                      {{ scope.row.status !== 'In Progress' ? 'Completed' : scope.row.status }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="Public" min-width="100">
                  <template slot-scope="scope">
                    <el-switch v-model="scope.row.isPublic"
                      @change="e => {scriptIsPublicChange(e, scope.row)}"
                      :disabled="scope.row.status === 'In Progress'"
                    ></el-switch>
                  </template>
                </el-table-column>
                <el-table-column label="Action" min-width="200">
                  <template slot-scope="scope">
                    <div class="action-btns">
                      <el-tooltip class="item" effect="dark" content="Detail" placement="top" transition="el-zoom-in-bottom">
                        <el-button type="text"
                          @click="jumpRolePage(scope.row, 'Screenwriter', 'script')"
                        >
                          <div class="img-btn project-detail"></div>
                        </el-button>
                      </el-tooltip>
                      <el-dropdown placement="bottom" @command="e => {scriptCommand(e, scope.row)}">
                        <el-button type="text" style="margin-left: 10px;">
                          <div class="img-btn more"></div>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                          <el-dropdown-item command="copy" :disabled="!scope.row.completed">
                            <div class="dropdown-item-div">
                              <span class="dropdown-item-icon copy"></span>
                              <span>Copy</span>
                            </div>
                          </el-dropdown-item>
                          <el-dropdown-item command="edit" :disabled="scope.row.status !== 'In Progress'">
                            <div class="dropdown-item-div">
                              <span class="dropdown-item-icon edit"></span>
                              <span>Edit</span>
                            </div>
                          </el-dropdown-item>
                          <el-dropdown-item command="complete" :disabled="scope.row.completed">
                            <div class="dropdown-item-div">
                              <span class="dropdown-item-icon complete"></span>
                              <span>Complete</span>
                            </div>
                          </el-dropdown-item>
                          <el-dropdown-item command="delete" divided :disabled="scope.row.status === 'In Production' || scope.row.status === 'Issued'">
                            <div class="dropdown-item-div">
                              <span class="dropdown-item-icon delete"></span>
                              <span>Delete</span>
                            </div>
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </el-dropdown>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="" width="20"></el-table-column>
              </el-table>
  
              <el-table class="collapse-table-body" :data="tableData[role].list" v-loading="tableData[role].tableLoading" v-else>
                <el-table-column label="" width="30"></el-table-column>
                <el-table-column label="Project Name" min-width="200">
                  <template slot-scope="scope">
                    <span>{{ scope.row.projectResponse.name }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="Project Team Member" min-width="300">
                  <template slot-scope="scope" v-if="scope.row.PRODUCER">
                    <div class="p-members-cell">
                      <div class="p-m-item producer">
                        <el-avatar class="member-avatar" :src="userInfoCach[scope.row.PRODUCER.userId].avatarImage" :size="50">{{ scope.row.PRODUCER.userId.slice(0, 1) }}</el-avatar>
                        <div class="p-m-right">
                          <span class="member-name">{{ scope.row.PRODUCER.userId }}</span>
                          <span class="member-roles">PRODUCER</span>
                        </div>
                      </div>
                      <el-popover placement="right" trigger="hover" @show="pMembersShow(scope.row)" transition="el-zoom-in-bottom">
                        <div
                          class="p-member-list"
                          v-loading="!scope.row.members || scope.row.members.length === 0"
                          v-infinite-scroll="
                            () => {
                              memberLoad(scope.row);
                            }
                          "
                          :infinite-scroll-disabled="infiniteScrollDisabled"
                          :infinite-scroll-immediate="false"
                        >
                          <el-row type="flex" style="flex-wrap: wrap; justify-content: flex-start;">
                            <el-col :span="scope.row.members.length > 5 ? 12 : 24" v-for="(m, ind) in scope.row.members" v-bind:key="ind">
                              <div class="p-m-item">
                                <el-avatar class="member-avatar" :src="userInfoCach[m.userId].avatarImage" :size="50">{{ m.userId.slice(0, 1) }}</el-avatar>
                                <div class="p-m-right">
                                  <span class="member-name">{{ m.userId }}</span>
                                  <span class="member-roles">{{ m.role }}</span>
                                </div>
                              </div>
                            </el-col>
                          </el-row>
                        </div>
                        <div class="p-m-avatars" slot="reference">
                          <div class="member-more"></div>
                          <div class="member-more"></div>
                          <div class="member-more"></div>
                        </div>
                      </el-popover>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="Project Status" min-width="300">
                  <template slot-scope="scope">
                    <div class="tag-div" :class="formatTagColor(scope.row.projectResponse.status)">
                      {{ scope.row.projectResponse.status }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="Action" min-width="200">
                  <template slot-scope="scope">
                    <div class="action-btns">
                      <el-tooltip class="item" effect="dark" content="Detail" placement="top" transition="el-zoom-in-bottom">
                        <el-button type="text"
                          @click="jumpRolePage(scope.row)"
                        >
                          <div class="img-btn project-detail"></div>
                        </el-button>
                      </el-tooltip>
                      <el-tooltip class="item" effect="dark" content="Member Setting" placement="top" transition="el-zoom-in-bottom">
                        <el-button type="text"
                          @click="pageJump('/filmmaking/producer/roleList', scope.row)"
                        >
                          <div class="img-btn member-set"></div>
                        </el-button>
                      </el-tooltip>
                      <el-dropdown placement="bottom" @command="e => {projectCommand(e, scope.row)}">
                        <el-button type="text" style="margin-left: 10px;">
                          <div class="img-btn more"></div>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                          <el-dropdown-item command="feedback" :disabled="!checkActionDisabled('Feedback', scope.row)">
                            <div class="dropdown-item-div">
                              <span class="dropdown-item-icon feedback"></span>
                              <span>Feedback</span>
                            </div>
                          </el-dropdown-item>
                          <el-dropdown-item command="upload" :disabled="!checkActionDisabled('Upload', scope.row)"
                            divided v-if="role === 'STORYTELLER' || role === 'VIDEOEDITOR' || role === 'VOICEACTOR' || role === 'DIRECTOR'"
                          >
                            <div class="dropdown-item-div">
                              <span class="dropdown-item-icon upload"></span>
                              <span>Upload</span>
                            </div>
                          </el-dropdown-item>
                          <el-dropdown-item command="sow" :disabled="!checkActionDisabled('SOW', scope.row)">
                            <div class="dropdown-item-div" v-if="!scope.row.signedSow">
                              <span class="dropdown-item-icon"></span>
                              <span>SOW</span>
                            </div>
                            <div class="dropdown-item-div" v-else>
                              <span class="dropdown-item-icon"></span>
                              <span>VIEW SOW</span>
                            </div>
                          </el-dropdown-item>
  
                          <el-dropdown-item command="publish" divided v-if="role === 'PRODUCER'"
                            :disabled="!checkActionDisabled('Publish', scope.row)">
                            <div class="dropdown-item-div">
                              <span class="dropdown-item-icon publish"></span>
                              <span>Publish</span>
                            </div>
                          </el-dropdown-item>
                          <el-dropdown-item command="pay" v-if="role === 'PRODUCER'" :disabled="!checkActionDisabled('Pay', scope.row)">
                            <div class="dropdown-item-div">
                              <span class="dropdown-item-icon pay"></span>
                              <span>Pay</span>
                            </div>
                          </el-dropdown-item>
                          <el-dropdown-item command="recruitment" v-if="role === 'PRODUCER'" :disabled="!checkActionDisabled('Recruitment', scope.row)">
                            <div class="dropdown-item-div" v-if="scope.row.projectResponse.recruitFlag">
                              <span class="dropdown-item-icon"></span>
                              <span>Complete Recruitment</span>
                            </div>
                            <div class="dropdown-item-div" v-else>
                              <span class="dropdown-item-icon"></span>
                              <span>Start Recruitment</span>
                            </div>
                          </el-dropdown-item>
  
                          <el-dropdown-item command="quit" divided v-if="role === 'PRODUCER'" :disabled="!checkActionDisabled('Dissolution Project', scope.row)">
                            <div class="dropdown-item-div">
                              <span class="dropdown-item-icon stop"></span>
                              <span>Dissolution Project</span>
                            </div>
                          </el-dropdown-item>
                          <el-dropdown-item command="quit" divided v-if="role !== 'PRODUCER'" :disabled="!checkActionDisabled('Quit Project', scope.row)">
                            <div class="dropdown-item-div">
                              <span class="dropdown-item-icon stop"></span>
                              <span>Quit Project</span>
                            </div>
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </el-dropdown>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="" width="20"></el-table-column>
              </el-table>
  
              <div class="pagination">
                <el-pagination
                  background
                  layout="prev, pager, next"
                  :hide-on-single-page="true"
                  :page-size="6"
                  :total="tableData[role].total"
                  @current-change="
                    e => {
                      paginationChange(e, role);
                    }
                  "
                ></el-pagination>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
  
      <publish-project ref="publishProject" @dialogClickOK="dialogClickOK"></publish-project>
  
      <CompleteScreenplay @emitInit="completeScreenplay_ok"
                          :isShow.sync="isShowCompleteScreenplay"
                          :scriptId="curScript.id"></CompleteScreenplay>
  
    </div>
  </template>
  
  <script>
  import cookie from 'js-cookie';
  import publishProject from '../../components/table/publishProject';
  
  export default {
    components: {
       publishProject,
    },
  
    computed: {
      userId() {
        return cookie.get('username');
      },
      userName() {
        return this.$store.state.username || cookie.get('username') || '';
      }
    },
    data() {
      return {
        rolesOrder: ['SCREENWRITER', 'PRODUCER', 'DIRECTOR', 'STORYTELLER', 'VOICEACTOR', 'VIDEOEDITOR'],
        tableData: {},
        role: '',
        userInfoCach: {},
        infiniteScrollDisabled: true,
        roles:['SCREENWRITER', 'PRODUCER', 'DIRECTOR', 'STORYTELLER', 'VOICEACTOR', 'VIDEOEDITOR'],
        curScript: {},
        isShowCompleteScreenplay: false,
      };
    },
    created() {
      this.pageInit();
    },
    mounted() {},
    methods: {
      pageInit() {
        this.roles.forEach(item => {
          if (!this.tableData[item]) {
            const roleData = {
              list: [],
              total: 0,
              tableLoading: false
            };
            this.$set(this.tableData, item, roleData);
          }
          this.getProjectDataByRole(item, 1);
        });
      },
      // 编剧表格行展开
      scTableExpandChange(row, expandedRows) {
        console.log(row, expandedRows)
        if (!expandedRows.map(e => e.id).includes(row.id)) {
          return;
        }
        const child = {
          list: [],
          total: 0,
          tableLoading: true,
        }
        this.$set(row, 'child', child);
        this.getProjectDataByRole('child', 1, row);
      },
  
      scriptIsPublicChange(e, row) {
        this.$message.success(`Operation successful`);
      },
  
      async getProjectDataByRole(role, page, row) {
        if (!role || role === '') {
          return;
        }
        if (role === 'child') {
          row.child.tableLoading = true;
        } else {
          this.tableData[role].tableLoading = true;
        }
        if (role === 'SCREENWRITER') {
          // const res = await this.$api.apiModules.getScriptList(this.userId, page, 6);
          // if (res.status === 200 && res.data?.content) {
          //   this.tableData[role].list = res.data.content;
          //   this.tableData[role].total = res.data.totalElements;
          //   this.tableData[role].tableLoading = false;
          //   this.tableData[role].page = page;
          // }
          return;
        }
  
        const params = {
          projectCompleted: '',
          userId: this.userId,
          userName: this.userName,
          key: role,
          page: page,
          pageSize: 6
        };
        let paramStr = `${params.projectCompleted}&userName=${params.userName}&userId=${params.userId}&pageNumber=${params.page}&pageSize=${params.pageSize}`;
        if (role === 'child') {
          paramStr = paramStr + `&scriptId=${row.id}&roles=SCREENWRITER`
        } else {
          paramStr = paramStr + `&roles=${params.key}`
        }
        // this.$api.apiModules.getProjectInfo(paramStr).then(res => {
        //   if (res.status === 200 && res.data?.content) {
        //     res.data.content.forEach(p => {
        //       this.$set(p, 'PRODUCER', { userId: p.projectResponse.userId });
        //       this.getAvatarImageByUserId(p.projectResponse.userId);
        //     });
        //     if (role === 'child') {
        //       row.child.total = res.data.totalElements;
        //       row.child.tableLoading = false;
        //       row.child.page = page;
        //       const newArr = res.data.content.map(item => {
        //         item.parentRow = row;
        //         return item;
        //       });
        //       row.child.list = newArr;
        //     } else {
        //       this.tableData[role].list = res.data.content;
        //       this.tableData[role].total = res.data.totalElements;
        //       this.tableData[role].tableLoading = false;
        //       this.tableData[role].page = page;
        //     }
        //     // this.getProducerByProjectId(this.tableData[role].list);
        //   }
        // });
      },
  
      // 查询制作人 项目详情中userId就是制作人，因为只有制作人才能创建项目。所以理论上不需要单独调用此方法
      getProducerByProjectId(projects) {
        if (!projects || projects.length === 0) {
          return;
        }
        const idStr = projects.map(item => `projectId=${item.projectId}`).join('&');
        const paramStr = `&${idStr}&userId=${this.userId}&roles=PRODUCER&pageNumber=1&pageSize=20`;
        // this.$api.apiModules.getProjectInfo(paramStr).then(res => {
        //   if (res.status === 200 && res.data?.content) {
        //     projects.forEach(p => {
        //       const oList = res.data.content;
        //       oList.forEach(o => {
        //         if (o.projectId === p.projectId) {
        //           this.$set(p, 'PRODUCER', { userId: o.userId });
        //           this.getAvatarImageByUserId(o.userId);
        //         }
        //       });
        //     });
        //   }
        // });
      },
  
      // 显示项目成员
      async pMembersShow(project) {
        if (!project) return;
        if (!project.members || project.page < 1) {
          this.infiniteScrollDisabled = true;
          this.$set(project, 'members', []); // 给每一条数据添加响应式成员属性
          project.page = 0;
          await this.memberLoad(project);
        } else {
        }
      },
  
      async memberLoad(project) {
        if (project.page === project.totalPages) {
          return;
        }
        const paramStr = `&projectId=${project.projectId}&userId=${this.userId}&pageNumber=${project.page + 1}&pageSize=10`;
        // const res = await this.$api.apiModules.getProjectInfo(paramStr);
        res.status = 400;
        if (res.status === 200 && res.data) {
          setTimeout(() => {
            this.infiniteScrollDisabled = false;
          }, 1000);
  
          project.page = res.data.page;
          project.totalPages = res.data.totalPages;
          const mList = res.data.content;
          mList.forEach(m => {
            project.members.push(m);
            this.getAvatarImageByUserId(m.userId);
          });
        }
      },
  
      async getAvatarImageByUserId(userId) {
        if (!this.userInfoCach[userId]) {
          this.$set(this.userInfoCach, userId, {});
          // const m = await this.$api.apiModules.getUserInfoByUserId(userId);
          const m={};
          if (m) {
            this.userInfoCach[userId] = m;
          }
        }
      },
  
      // 切换页码
      paginationChange(e, role, row) {
        this.getProjectDataByRole(role, e, row);
      },
  
      pageJump(path, project) {
        this.$router.push({ path: path, query: { projectId: project.projectId, projectRole: project.role } });
      },
  
      formatTagColor(status) {
        if (status === 'Published' || status === 'To Be Invested' || status === 'In Production' || status === 'Issued') {
          return 'tag-completed';
        }
        if (status === 'Voice acting' || status === 'Project completed' || status === 'Final cut') {
          return 'tag-doing';
        }
        if (status === 'Pending Recruitment' || status === 'Recruit project members' || status === 'Pending payment') {
          return 'tag-pending';
        }
        return 'tag-default';
      },
      // 检测按钮功能是否可用 ['SCREENWRITER', 'PRODUCER', 'DIRECTOR', 'STORYTELLER', 'VOICEACTOR', 'VIDEOEDITOR'],
      checkActionDisabled(type, row) {
        if (type === 'Feedback') {
          return (
            false
        
          );
        }
        if (type === 'Upload') {
          return (
            (row.role === "STORYTELLER" && row.projectResponse.status === 'Animation') ||
            (row.role === "VOICEACTOR" && row.projectResponse.status === 'Voice acting') ||
            (row.role === "VIDEOEDITOR" && row.projectResponse.status === 'First cut') ||
            (row.role === "DIRECTOR" && row.projectResponse.status === 'Final cut')
          )
        }
        if (type === 'SOW') {
          return (
            row.projectResponse.status !== 'Pending payment' &&
            row.projectResponse.status !== 'Payment to be confirmed' &&
            row.projectResponse.status !== 'Pending Recruitment' &&
            row.projectResponse.status !== 'Recruit project members'
          ) && (
            !row.isFired && !row.earlyTermination
          );
        }
        if (type === 'Publish') {
          return row.projectResponse.completed && !row.projectResponse.published;
        }
        if (type === 'Pay') {
          return row.projectResponse.status === 'Pending payment'
        }
        if (type === 'Recruitment') {
          return row.projectResponse.status === 'Pending Recruitment' || row.projectResponse.recruitFlag
        }
        if (type === 'Quit Project') {
          return !row.projectResponse.completed && !row.isFired && !row.earlyTermination;
        }
        if (type === 'Dissolution Project') {
          return !row.projectResponse.completed && !row.isFired && !row.earlyTermination;
        }
        return false;
      },
  
      async scriptCommand(e, row) {
        console.log(e, row);
        if (e === 'copy') {
          this.$prompt('Script Name', 'Please name the copied script', {
            confirmButtonText: 'Submit',
            cancelButtonText: 'Cancel',
            beforeClose: (action, instance, done) => {
              if (action === 'confirm' && !instance.inputValue) {
                this.$message.error(`Please input  the Script name`);
              } else {
                done();
              }
            },
          }).then(({ value }) => {
            this.$api.apiModules.copyScriptData(row.id, this.userId, {
              scriptId: row.id,
              scriptName: value,
            }).then(res => {
              if (res.status === 200) {
                this.$message.success('Copy Success');
                this.getProjectDataByRole('SCREENWRITER', this.tableData['SCREENWRITER'].page);
              }
            });
          }).catch(() => {
  
          });
        }
        if (e === 'edit') {
          this.$router.push({ path: `/filmmaking/screenWriter/bible?id=${row.id}`});
        }
        if (e === 'complete') {
          this.curScript = row;
          // ============================ old  code ============================
          const id = row.id;
          const story = await this.getStoryData(id);
          const asset = await this.getAssetData(id);
          const screenplayScenes = await this.getScreenplayData(id);
          // story 或者 asset 或者screenplay 没填写情况
          if (!story || !asset || !screenplayScenes) {
            return this.$message.error('Failed to input scirpt~');
          }
          // screenplay 没填写情况
          if (screenplayScenes && screenplayScenes.length === 0) {
            return this.$message.error('Failed to input screenplay~');
          }
          // screenplay 有header没填写情况
          if (!this.checkScreenplay(screenplayScenes.scenes)) {
            return this.$message.error('Failed to input screenplay~');
          }
          // asset 没填写情况
          if (asset && asset.scene && asset.scene.length === 0) {
            return this.$message.error('Failed to input asset scene~');
          }
          // asset 没填写情况
          if (asset && asset.character && asset.character.length === 0) {
            return this.$message.error('Failed to input asset character~');
          }
          // asset 第几个人物没填写情况
          for (let i = 0; i < asset.character.length; i++) {
            if (!asset.character[i].name) {
              let str = '';
              if (i + 1 === 1) {
                str = `The 1st character's name needs to be filled！`;
              }
              if (i + 1 === 2) {
                str = `The 2nd character's name needs to be filled！`;
              }
              if (i + 1 === 3) {
                str = `The 3rd character's name needs to be filled！`;
              }
              if (i + 1 >= 4) {
                str = `The ${i + 1}th character's name needs to be filled！`;
              }
              this.$message.error(str);
              return false;
            }
          }
          this.isShowCompleteScreenplay = true;
          // ============================ old  code end============================
        }
        if (e === 'delete') {
          this.$confirm('This operation will permanently delete the script, do you want to continue?', 'Tip', {
            confirmButtonText: 'Delete',
            cancelButtonText: 'Cancel',
            type: 'warning'
          }).then(() => {
            this.$api.apiModules.deleteScriptData(row.id, this.userId).then(res => {
              if (res.status === 200) {
                this.$message.success(`Operation successful`);
                this.getProjectDataByRole('SCREENWRITER', this.tableData['SCREENWRITER'].page);
              }
            })
          }).catch(() => {});
        }
      },
      // ============================ old  code start============================
      async getStoryData(scriptId) {
        const res = await this.$axios({
          url: `/api/corebackend/script/${scriptId}/story-bible?userId=${this.userId}`,
          method: 'GET',
        });
        const data = res.data;
        return data;
      },
      async getAssetData(scriptId) {
        const res = await this.$axios({
          url: `/api/corebackend/script/${scriptId}/asset-bible?userId=${this.userId}`,
          method: 'GET',
        });
        const data = res.data;
        let sceneList = [];
        data.assetBibleScenes.forEach((item) => {
          if (item.previewPath) {
            sceneList.push(item);
          }
        });
  
        let characterList = [];
        data.assetBibleCharacters.forEach((item) => {
          if (item.path) {
            characterList.push(item);
          }
        });
        return {
          scene: sceneList,
          character: characterList,
        };
      },
      async getScreenplayData(scriptId) {
        const res = await this.$axios({
          url: `/api/corebackend/script/${scriptId}/screenplays?userId=${this.userId}`,
          method: 'GET',
        });
        if (res.data && res.data.length) {
          const screenplay = res.data[0];
          if (screenplay.totalWordCount !== undefined) {
            delete screenplay.totalWordCount;
          }
          return screenplay;
        }
      },
      checkScreenplay(scenes) {
        for (let i = 0; i < scenes.length; i++) {
          const scene = scenes[i];
          if (!scene.header) {
            this.$message.error(`Please add Header into scene ${i + 1}`);
            return false;
          }
        }
        return true;
      },
      //根据角色跳转不同详情页
      jumpRolePage(item, key, keyword) {
        console.log(item)
        if (item.role === 'Producer' || item.role === 'PRODUCER') {
          item.child = '';
          this.$router.push({path: `/filmmaking/producer?tabsId=0`, query: {producerInfo: JSON.stringify(item)}});
        } else if (key === 'Screenwriter') {
          item.child = '';
          this.$router.push({
            path: `/filmmaking/screenWriter?id=${item.id}`,
            query: {
              screenWriterInfo: JSON.stringify(item),
              keyword,
            },
          });
        } else if (item.role === 'VOICEACTOR') {
          item.child = '';
          this.$router.push({path: `/filmmaking/voiceActor?tabsId=0`, query: {projectId: item.projectId}});
        } else if (item.role === 'DIRECTOR') {
          item.child = '';
          this.$router.push({path: `/filmmaking/director?tabsId=0`, query: {directorInfo: JSON.stringify(item)}});
        } else if (item.role === 'STORYTELLER') {
          item.child = '';
          this.$router.push({path: `/filmmaking/storyteller?tabsId=0`, query: {storytellerInfo: JSON.stringify(item)}});
        } else if (item.role === 'VIDEOEDITOR') {
          item.child = '';
          this.$router.push({path: `/filmmaking/videoEditor?tabsId=0`, query: {videoEditorInfo: JSON.stringify(item)}});
        }
      },
      // ============================ old  code ============================
  
      async projectCommand(e, row, type) {
        console.log(e, row);
        if (e === 'recruitment') {
          if (row.projectResponse.recruitFlag) {  // 完成招聘
            const r = await this.$api.apiModules.checkJobsRecruitment(this.userId, row.projectId);
            if (r.status !== 200) return;
            if (r.data?.content?.length > 0) {
              const jobIds = r.data.content.map(item => item.id);
              const r1 = await this.$api.apiModules.closeRecruitmentByJob(this.userId, {jobIds});
              if (r1.status !== 200) return;
            }
            this.updateRecruitmentStatus(row, false);
  
          } else { // 开始招聘
            const r1 = await this.$api.apiModules.startRecruitment(this.userId, {
              projectId: row.projectId,
            });
            if (r1.status !== 200) return;
            this.updateRecruitmentStatus(row, true);
          }
        }
        if (e === 'pay'){
          this.producerPay(row);
        }
        if (e === 'publish'){
          this.$refs.publishProject.dialogShow(true, row);
        }
        if (e === 'upload'){
          if (row.role === 'VOICEACTOR') {
            this.$router.push({path: `/filmmaking/voiceActor?tabsId=3`, query: {projectId: row.projectId}});
          } else if (row.role === 'DIRECTOR') {
            this.$router.push({path: `/filmmaking/director?tabsId=6`, query: {directorInfo: JSON.stringify(row)}});
          } else if (row.role === 'STORYTELLER') {
            this.$router.push({path: `/filmmaking/storyteller?tabsId=4`, query: {storytellerInfo: JSON.stringify(row)}});
          } else if (row.role === 'VIDEOEDITOR') {
            this.$router.push({path: `/filmmaking/videoEditor?tabsId=3`, query: {videoEditorInfo: JSON.stringify(row)}});
          }
        }
      },
      // 更新招聘状态
      updateRecruitmentStatus(row, value) {
        this.$api.apiModules.updateRecruitmentStatus(this.userId, row.projectId, {
          recruitFlag: value,
        }).then(res => {
          if (res.status !== 200) return;
          this.$message.success(`Operation successful`);
          this.getProjectDataByRole(row.role, this.tableData[row.role].page);
        })
      },
      // 弹窗关闭 更新 当页数据
      dialogClickOK(row) {
        if (row.isChild) {
          this.getProjectDataByRole('child', row.parentRow.child.page, row.parentRow);
        } else {
          this.getProjectDataByRole(row.role, this.tableData[row.role].page);
        }
      },
      completeScreenplay_ok() {
        this.getProjectDataByRole('SCREENWRITER', this.tableData['SCREENWRITER'].page);
      },
  
      // 制作人支付
      async producerPay(row) {
        const r1 = await this.$api.apiModules.getScriptInfoById(row.projectResponse.scriptId, this.userId);
        if (r1.status !== 200) return;
        const scriptInfo = r.data;
        const url = window.location.origin;
        const checkParams = {
          cancelUrl: url + '/pay/error',
          returnUrl: url + '/pay/success',
          currency: 'USD',
          description: 'description',
          projectId: row.projectId,
          username: this.userId,
          value: scriptInfo.deposit,
        }
        const r2 = await this.$api.apiModules.paymentCheckout(this.userId, checkParams);
        if (r2.data?.id && r2.data?.links) {
          //为了给支付成功/失败使用的
          const info = {
            scriptName: scriptInfo.name,
            scriptDeposit: scriptInfo.deposit,
            projectName: row.projectResponse.name,
            projectStartTime: row.projectResponse.startingTime,
            projectEndTime: row.projectResponse.endingTime,
            orderId: r2.data.id,
            type: 2,
          };
          let paypayUrl = '';
          r2.data.links.forEach((item) => {
            if (item.rel === 'approve') {
              item.issss = 1;
              paypayUrl = item.href;
            }
          });
          info.paypayUrl = paypayUrl;
          cookie.set('projectPayInfo', JSON.stringify(info));
          window.open(paypayUrl, '_self');
        }
      },
    }
  };
  </script>
  
  <style lang="less" scoped>
  .project-collapse {
    padding: 30px 0;
    background: #ffffff;
    border-radius: 18px;
    margin-bottom: 18px;
    box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.02);
    .pagination {
      display: flex;
      justify-content: flex-end;
      padding: 0px 30px 0 0;
      /deep/ .el-pagination{
        padding-top: 12px;
      }
    }
    .p-members-cell {
      display: flex;
      align-items: center;
  
      .p-m-avatars {
        margin-left: 20px;
        position: relative;
        height: 25px;
        width: 40px;
        .member-more {
          position: absolute;
          top: 0;
          width: 25px;
          height: 25px;
          border-radius: 50%;
          background-repeat: no-repeat;
          background-size: 90% 90%;
          cursor: pointer;
          box-shadow: -3px 0px 12px 0px rgba(0, 0, 0, 0.05);
          border: 2px solid #ffffff;
          background-color: #e8e8e8;
          background-position: center;
          &:nth-child(1) {
            left: 0;
          }
          &:nth-child(2) {
            left: 7px;
          }
          &:nth-child(3) {
            left: 14px;
            background-image: url('~/static/icon/more.png');
          }
        }
      }
    }
    .action-btns {
      .img-btn {
        display: inline-block;
        width: 24px;
        height: 24px;
        background-size: 100% 100%;
        background-repeat: no-repeat;
        &.member-set {
          background-image: url('~/static/icon/producer_table_group_setting.png');
        }
        &.project-detail {
          background-image: url('~/static/icon/producer_table_detail.png');
        }
        &.more {
          background-image: url('~/static/icon/more.png');
        }
      }
      /deep/ .el-button.is-disabled.el-button--text {
        filter: grayscale(0.7) brightness(2.4);
      }
    }
  
    .collapse-head-slot {
      display: flex;
      flex: 1;
      justify-content: space-between;
      padding: 0 40px;
      .collapse-head-title {
        font-size: 22px;
        // .collapse-head-icon{
        //   font-size: 18px;
        // }
      }
    }
    .collapse-table-body {
      width: 100%;
      background: #fcfcfc;
      /deep/ .el-table__body {
        .cell {
          height: 58px;
          display: flex;
          align-items: center;
        }
      }
      /deep/ .el-table__row {
        background: transparent;
      }
      /deep/ .el-table__header{
        .cell {
          font-weight: bold;
        }
      }
    }
  
    /deep/ .el-collapse-item__header {
      border: none;
      .el-collapse-item__arrow.el-icon-arrow-right {
        margin-right: 40px;
        font-size: 18px;
      }
      // &.is-active{
      //   .collapse-head-icon{
      //     transform: rotateZ(90deg);
      //   }
      // }
    }
    /deep/ .el-collapse {
      border: none;
      .el-collapse-item__wrap {
        border: none;
      }
      .el-collapse-item__content {
        padding-bottom: 0;
      }
    }
  
    .sc-child-table-div{
      padding: 10px 40px;
      .child-table-body{
        /deep/ .el-table__header{
          .cell {
            height: auto;
          }
        }
      }
    }
  
    .tag-div{
      padding: 5px 10px;
      &.tag-completed{
        color: rgb(0 153 255);
        background-color: rgb(0 153 255 / 10%);
        border: 1px solid rgb(0 153 255 / 12%);
        border-radius: 4px;
      }
      &.tag-doing{
        color: rgb(21 190 0);
        background-color: rgb(21 190 0 / 10%);
        border: 1px solid rgb(21 190 0 / 12%);
        border-radius: 4px;
      }
      &.tag-pending{
        color: rgb(255 130 0);
        background-color: rgb(255 130 0 / 10%);
        border: 1px solid rgb(255 130 0 / 12%);
        border-radius: 4px;
      }
      &.tag-default{
        color: rgb(153 153 153);
        background-color: rgb(153 153 153 / 10%);
        border: 1px solid rgb(153 153 153 / 12%);
        border-radius: 4px;
      }
    }
  }
  .dropdown-item-div {
    display: flex;
    align-items: center;
    .dropdown-item-icon {
      display: inline-block;
      width: 21px;
      height: 21px;
      background-repeat: no-repeat;
      background-size: 100% 100%;
      margin-right: 16px;
      &.copy {
        background-image: url('~/static/icon/copy.png');
      }
      &.edit {
        background-image: url('~/static/icon/edit.png');
      }
      &.delete {
        background-image: url('~/static/icon/common_del.png');
      }
      &.complete {
        background-image: url('~/static/icon/complete.png');
      }
      &.pay {
        background-image: url('~/static/icon/pay.png');
      }
      &.publish {
        background-image: url('~/static/icon/publish.png');
      }
      &.feedback {
        background-image: url('~/static/icon/common_feedback.png');
      }
      &.stop {
        background-image: url('~/static/icon/stop.png');
      }
      &.upload {
        background-image: url('~/static/icon/upload.png');
      }
    }
  }
  /deep/ .el-dropdown-menu__item.is-disabled{
    .dropdown-item-icon{
      filter: grayscale(0.7) brightness(1.5);
    }
  }
  
  .p-m-item {
      display: flex;
      align-items: center;
      .p-m-right {
        display: flex;
        flex-direction: column;
        flex: 1;
        min-height: 58px;
        justify-content: center;
        .member-name {
          font-size: 14px;
          color: #606266;
        }
        .member-roles {
          font-size: 12px;
          color: #aaaaaa;
        }
      }
    }
    .member-avatar {
      border: 3px solid #ffffff;
      margin: 4px 10px 4px 0;
      display: flex;
      justify-content: center;
      align-items: center;
      box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
    }
    .p-member-list {
      min-width: 200px;
      min-height: 136px;
      max-height: 300px;
      max-width: 500px;
      overflow-y: auto;
      .p-m-item {
        min-width: 100px;
        align-items: flex-start;
        padding: 5px 10px;
        width: fit-content;
      }
    }
  
  </style>
  